package com.controller;


import com.config.api.UploadResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class UploadController {

    @Resource
    UploadResult uploadResult;

    @Resource
    UploadResult.DataBean dataBean;
    /**
     * 使用UUID类提供的静态方法randomUUID() 得到一个id
     * UUID: A class that represents an immutable universally unique identifier (UUID).
     * A UUID represents a 128-bit value.
     * length: 32
     * @return 随机id，32位字符串
     */
    public static String getId() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }
    /**
     * 执行文件上传
     */
    @PostMapping("/admin/good/fileUpload")
    @ResponseBody
    public UploadResult handleFormUpload(@RequestParam("file") List<MultipartFile> uploadfile,
                                         HttpServletRequest request) {
        // 判断所上传文件是否存在
        if (!uploadfile.isEmpty()) {
            //循环输出上传的文件
            for (MultipartFile file : uploadfile) {
                // 设置上传文件的保存地址目录
                try {
                    String dirPath = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
                    //request.getServletContext().getRealPath("/static/upload/");
                    File filePath = new File(dirPath);
                    // 如果保存文件的地址不存在，就先创建目录
                    if (!filePath.exists()) {
                        filePath.mkdirs();//创建文件目录
                    }
                    // 新图片的名称getOriginalFilename为图片名称
                    String originFileName = file.getOriginalFilename();// 获取上传文件的原始名称
                    assert originFileName != null;
                    String newFileName = getId() +
                            originFileName.substring(originFileName.lastIndexOf("."));
                    // 使用MultipartFile接口的方法完成文件上传到指定位置
                    file.transferTo(new File(dirPath +"/"+ newFileName));
                    dataBean.setSrc("/static/upload/" + newFileName);
                } catch (Exception e) {
                    e.printStackTrace();
                    uploadResult.setCode(1);
                    uploadResult.setMsg(e.getMessage());
                }
            }
            // 上传成功
            uploadResult.setCode(0);
            uploadResult.setData(dataBean);
            uploadResult.setMsg("上传成功");
        }else{
            uploadResult.setCode(1);
            uploadResult.setMsg("图片不存在");
        }
        return uploadResult;
    }
    /**
     * 传入图片并储存在对应文件夹
     * @param mv
     * @param pic
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/uploadTest")
    public ModelAndView uploadTest(ModelAndView mv, MultipartFile pic, HttpServletRequest request)
            throws IllegalStateException, IOException {
        String FILE_TARGET = "target";
        String basePath = request.getSession().getServletContext().getRealPath("/"); // "/": 表示获取根目录
        basePath = basePath.substring(0,basePath.lastIndexOf(FILE_TARGET));
        String path = basePath + "web/upload/";
        System.out.println(path);
        // 新图片的名称
        String originFileName = pic.getOriginalFilename();
        assert originFileName != null;
        String newFileName = getId() +
                originFileName.substring(originFileName.lastIndexOf("."));
        // 新的图片
        File newFile = new File(path + newFileName);
        // 将内存中的数据写入磁盘
        pic.transferTo(newFile);
        return mv;
    }
}
